<?php

class WebUser extends CWebUser{

    protected $_model;
	protected $_perms;

	public function init() {
		$conf = Yii::app()->session->cookieParams;
        $this->identityCookie = array(
            'path' => $conf['path'],
            'domain' => $conf['domain'],
        );
        parent::init();
	}

    function isAdmin(){
        $user = $this->loadUser(Yii::app()->user->id);
		return $user->user_type == 'A';
    }

	function getFirstName(){
		$user = $this->loadUser(Yii::app()->user->id);
		return $user->name;
	}

    // Load user model.
    protected function loadUser($user_id=null)
    {
        if ($user_id!==null) $this->_model=User::model()->findByPk($user_id);
        return $this->_model;
    }

	function checkPerm($perm) {
		if ( $this->isGuest ) return false;

		if ( app()->user->id == 1 ) return true; // root admin => full access

		if ( $this->_perms === null ) {
			if ( $this->_model === null ) {
				$this->loadUser(Yii::app()->user->id);
			}

			$perms = array();
			$usergroups = $this->_model->usergroups;
			if ( !empty($usergroups) ) {
				foreach ($usergroups as $usergroup) {
					$privileges = Usergroup::getGroupPrivileges($usergroup->usergroup_id);
					$perms = array_merge($perms, $privileges);
				}
			}

			$perms = array_unique($perms);
			$this->_perms = array_flip($perms);
		}

		if ( isset($this->_perms[$perm]) ) {
			return true;
		}

		return false;
	}

	function setNotification($type, $title, $message, $save_state = false) {
		$key = md5($type . $title . $message . $save_state);
		$flash = array(
			'type' => $type,
			'title' => $title,
			'message' => $message,
			'save_state' => $save_state,
		);

		parent::setFlash($key, $flash);
	}

	function getNotifications() {
		$notifications = user()->getFlashes();
		return $notifications;
	}
}